package mapeditor.mappanel;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.JPanel;

public class DrawingArea extends JPanel {

	private int sqs = 20;
	private int sqsHeight = 35;
	private Image offScreen;
	private Graphics gg;
	private boolean isFirst = true;
	private int selectX = -1, selectY = -1, selectX2 = -1, selectY2 = -1;
	private boolean isSelecting = false;

	private Point click;

	public DrawingArea() {
		addMouseMotionListener(new MapMouseMotionListener(this));
		addMouseListener(new MapMouseListener(this));
		repaint();
	}

	public void clickAt(Point p) {
		click = p;
	}

	public void selectingChange(boolean b, int x, int y, int x2, int y2) {
		isSelecting = b;
		selectX = x;
		selectY = y;
		selectX2 = x2;
		selectY2 = y2;
	}

	public void paint(Graphics g) {
		if (isFirst) {
			offScreen = createImage(this.getWidth(), this.getHeight());
			gg = offScreen.getGraphics();
			isFirst = false;
		}

		// all map
		for (int i = 0; i < sqs; i++) {
			for (int j = 0; j < sqs; j++) {
				double ratio = ((i * j) / (double) (sqs * sqs));
				int c = (int) (255 * ratio);
				gg.setColor(new Color(255 - c, 0, 0));
				gg.fillRect(i * sqsHeight, j * sqsHeight, sqsHeight, sqsHeight);
			}
		}
		// where courser currently is
		if (click != null) {
			gg.setColor(Color.green);
			gg.fillRect(((int) (click.getX()) / sqsHeight) * sqsHeight,
					((int) (click.getY()) / sqsHeight) * sqsHeight, sqsHeight,
					sqsHeight);
		}

		if (isSelecting) {
			// is currently marking up area
			int width = Math.abs(selectX - selectX2);
			int height = Math.abs(selectY - selectY2);
			int toPaintAtX = 0;
			int toPaintAtY = 0;

			int x = selectX < selectX2 ? selectX : selectX2;
			int y = selectY < selectY2 ? selectY : selectY2;

			toPaintAtX = selectX % sqsHeight > 0 ? toPaintAtX + 1 : toPaintAtX;
			toPaintAtX = selectX2 % sqsHeight > 0 ? toPaintAtX + 1 : toPaintAtX;

			toPaintAtY = selectY % sqsHeight > 0 ? toPaintAtY + 1 : toPaintAtY;
			toPaintAtY = selectY2 % sqsHeight > 0 ? toPaintAtY + 1 : toPaintAtY;

			toPaintAtX += (width - Math.abs(selectX % sqsHeight) - Math
					.abs(selectX2 % sqsHeight)) / sqsHeight;

			toPaintAtY += (height - Math.abs(selectY % sqsHeight) - Math
					.abs(selectY2 % sqsHeight)) / sqsHeight;

			// if (selectX%sqsHeight>=sqsHeight/2 && toPaintAtX>=2){
			// toPaintAtX++;
			// }
			// if (selectY%sqsHeight>=sqsHeight/2 && toPaintAtY>=2){
			// toPaintAtY++;
			// }
			for (int i = 0; i < toPaintAtX; i++) {
				for (int j = 0; j < toPaintAtY; j++) {
					gg.setColor(Color.green);
					gg.fillRect(x - (x % sqsHeight) + (i * sqsHeight), y
							- (y % sqsHeight) + (j * sqsHeight), sqsHeight,
							sqsHeight);
				}
			}

			gg.setColor(Color.black);
			gg.drawRect(x, y, width, height);
		}
		g.drawImage(offScreen, 0, 0, this);
	}

	public void update(Graphics g) {
		paint(g);
	}

}
